<template>
  <div class="home-container">
    <el-row :gutter="20">
      <el-col :span="16">
        <el-card class="upload-card">
          <template #header>
            <div class="card-header">
              <h3>
                <el-icon><Upload /></el-icon>
                PDF文件上传
              </h3>
            </div>
          </template>
          
          <el-upload
            ref="uploadRef"
            class="upload-area"
            drag
            :auto-upload="false"
            :on-change="handleFileChange"
            :before-upload="beforeUpload"
            :file-list="fileList"
            accept=".pdf"
            :limit="1"
          >
            <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
            <div class="el-upload__text">
              将PDF文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                只能上传PDF文件，且不超过50MB
              </div>
            </template>
          </el-upload>
          
          <div class="upload-actions" v-if="selectedFile">
            <el-button
              type="primary"
              :loading="converting"
              @click="handleConvert"
              size="large"
            >
              <el-icon><VideoPlay /></el-icon>
              开始转换
            </el-button>
            <el-button @click="clearFile" size="large">
              清除文件
            </el-button>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="info-card">
          <template #header>
            <div class="card-header">
              <h3>
                <el-icon><InfoFilled /></el-icon>
                使用说明
              </h3>
            </div>
          </template>
          
          <div class="info-content">
            <el-steps direction="vertical" :active="1">
              <el-step title="上传PDF文件" description="选择或拖拽PDF文件到上传区域" />
              <el-step title="开始转换" description="点击转换按钮，系统将PDF转换为PPT" />
              <el-step title="下载PPT" description="转换完成后，可以下载生成的PPT文件" />
            </el-steps>
            
            <el-divider />
            
            <div class="features">
              <h4>功能特点：</h4>
              <ul>
                <li>支持多页PDF转换</li>
                <li>每页PDF生成一页PPT</li>
                <li>保持原始页面布局</li>
                <li>高质量图像输出</li>
                <li>快速转换处理</li>
              </ul>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 转换进度对话框 -->
    <el-dialog
      v-model="progressVisible"
      title="转换进度"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      width="400px"
    >
      <div class="progress-content">
        <el-progress
          :percentage="progressPercentage"
          :status="progressStatus"
          :stroke-width="10"
        />
        <p class="progress-text">{{ progressText }}</p>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="conversionStatus === 'COMPLETED'"
            type="primary"
            @click="downloadPpt"
          >
            下载PPT
          </el-button>
          <el-button
            v-if="conversionStatus === 'FAILED'"
            @click="progressVisible = false"
          >
            关闭
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { convertApi } from '../api/auth'

export default {
  name: 'Home',
  setup() {
    const uploadRef = ref()
    const fileList = ref([])
    const selectedFile = ref(null)
    const converting = ref(false)
    const progressVisible = ref(false)
    const progressPercentage = ref(0)
    const progressStatus = ref('')
    const progressText = ref('准备转换...')
    const conversionStatus = ref('')
    const currentConversionId = ref('')

    const handleFileChange = (file) => {
      selectedFile.value = file.raw
    }

    const beforeUpload = (file) => {
      const isPDF = file.type === 'application/pdf'
      const isLt50M = file.size / 1024 / 1024 < 50

      if (!isPDF) {
        ElMessage.error('只能上传PDF文件!')
        return false
      }
      if (!isLt50M) {
        ElMessage.error('文件大小不能超过50MB!')
        return false
      }
      return false // 阻止自动上传
    }

    const clearFile = () => {
      selectedFile.value = null
      fileList.value = []
      if (uploadRef.value) {
        uploadRef.value.clearFiles()
      }
    }

    const handleConvert = async () => {
      if (!selectedFile.value) {
        ElMessage.warning('请先选择PDF文件')
        return
      }

      try {
        converting.value = true
        progressVisible.value = true
        progressPercentage.value = 0
        progressStatus.value = ''
        progressText.value = '正在上传文件...'

        const response = await convertApi.upload(selectedFile.value)
        
        if (response.data.success) {
          currentConversionId.value = response.data.data.id
          progressPercentage.value = 30
          progressText.value = '文件上传成功，开始转换...'
          
          // 开始轮询转换状态
          await pollConversionStatus()
        } else {
          throw new Error(response.data.message)
        }
      } catch (error) {
        ElMessage.error('转换失败: ' + (error.message || '未知错误'))
        progressVisible.value = false
      } finally {
        converting.value = false
      }
    }

    const pollConversionStatus = async () => {
      const maxAttempts = 60 // 最多轮询60次（5分钟）
      let attempts = 0

      const poll = async () => {
        try {
          const response = await convertApi.status(currentConversionId.value)
          const conversion = response.data.data
          
          conversionStatus.value = conversion.status
          
          switch (conversion.status) {
            case 'PENDING':
              progressPercentage.value = 40
              progressText.value = '等待处理...'
              break
            case 'PROCESSING':
              progressPercentage.value = 60
              progressText.value = '正在转换PDF页面...'
              break
            case 'COMPLETED':
              progressPercentage.value = 100
              progressStatus.value = 'success'
              progressText.value = '转换完成！'
              return
            case 'FAILED':
              progressPercentage.value = 100
              progressStatus.value = 'exception'
              progressText.value = '转换失败: ' + (conversion.errorMessage || '未知错误')
              return
          }
          
          attempts++
          if (attempts < maxAttempts) {
            setTimeout(poll, 2000) // 每2秒轮询一次
          } else {
            progressText.value = '转换超时，请稍后重试'
            progressStatus.value = 'exception'
          }
        } catch (error) {
          progressText.value = '获取转换状态失败'
          progressStatus.value = 'exception'
        }
      }
      
      await poll()
    }

    const downloadPpt = async () => {
      try {
        const response = await convertApi.download(currentConversionId.value)
        
        // 创建下载链接
        const blob = new Blob([response.data], { 
          type: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' 
        })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = selectedFile.value.name.replace('.pdf', '.pptx')
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
        
        ElMessage.success('PPT文件下载成功')
        progressVisible.value = false
        clearFile()
      } catch (error) {
        ElMessage.error('下载失败: ' + (error.message || '未知错误'))
      }
    }

    return {
      uploadRef,
      fileList,
      selectedFile,
      converting,
      progressVisible,
      progressPercentage,
      progressStatus,
      progressText,
      conversionStatus,
      handleFileChange,
      beforeUpload,
      clearFile,
      handleConvert,
      downloadPpt
    }
  }
}
</script>

<style scoped>
.home-container {
  max-width: 1200px;
  margin: 0 auto;
}

.upload-card, .info-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.card-header h3 {
  margin: 0;
  color: #409EFF;
}

.upload-area {
  width: 100%;
}

.upload-actions {
  margin-top: 20px;
  text-align: center;
}

.info-content {
  padding: 10px 0;
}

.features h4 {
  margin: 0 0 10px 0;
  color: #409EFF;
}

.features ul {
  margin: 0;
  padding-left: 20px;
}

.features li {
  margin-bottom: 5px;
  color: #606266;
}

.progress-content {
  text-align: center;
}

.progress-text {
  margin-top: 15px;
  color: #606266;
}

.dialog-footer {
  text-align: center;
}

:deep(.el-upload-dragger) {
  width: 100%;
  height: 200px;
}

:deep(.el-upload__tip) {
  color: #909399;
}
</style> 